package com.yztstudy.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yztstudy.Mapper.AddressMapper;
import com.yztstudy.Service.AddressService;
import com.yztstudy.entity.Address;
import com.yztstudy.param.AddressListParam;
import com.yztstudy.param.AddressRemoveParam;
import com.yztstudy.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户地址的实现类
 */

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;


    /**
     * TODO 查询某个用户的全部地址
     * @param addressListParam 前端传过来的用户主键
     * @return
     */
    @Override
    public R list(AddressListParam addressListParam) {

        // TODO 1.封装查询参数
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", addressListParam.getUserId());
        List<Address> addresses = addressMapper.selectList(wrapper);

        // TODO 2.结果返回
        log.info("AddressServiceImpl.list业务结束, 结果:{}", "查询成功!");
        return R.ok("查询成功!", addresses);
    }


    /**
     * TODO 保存用户新增的地址
     * @param address 前端发过来的地址对象
     * @return
     */
    @Override
    public R save(Address address) {

        // TODO 1.插入数据
        int rows = addressMapper.insert(address);
        if (rows == 0)
        {
            log.info("AddressServiceImpl.save业务结束, 结果:{}", "插入地址失败!");
            return R.fail("插入地址失败!");
        }

        // TODO 2.如果插入成功
        AddressListParam param = new AddressListParam();
        param.setUserId(address.getUserId());
        log.info("AddressServiceImpl.save业务结束, 结果:{}", "插入地址成功!");
        return this.list(param);
    }


    /**
     * TODO 删除用户的某个地址
     * @param addressRemoveParam 前端发过来的地址主键
     * @return
     */
    @Override
    public R remove(AddressRemoveParam addressRemoveParam) {

        // TODO 1.删除数据
        int rows = addressMapper.deleteById(addressRemoveParam.getId());
        if (rows == 0)
        {
            log.info("AddressServiceImpl.remove业务结束, 结果:{}", "删除地址失败!");
            return R.fail("删除地址失败!");
        }

        // TODO 2.如果删除成功
        log.info("AddressServiceImpl.remove业务结束, 结果:{}", "删除地址成功!");
        return R.ok("删除地址成功!");
    }
}
